package controllers;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

import models.CategoryModel;
import models.LinkModel;
import models.UserModel;

import data.CategoryData;
import data.LinkData;
import data.UserData;
import forms.LinkForm;

public class EditLinkServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		TreeMap check = new TreeMap();
		CategoryData cData = new CategoryData();
		ArrayList<CategoryModel> categories = cData.list();
		LinkData linkData = new LinkData();
		LinkModel link = new LinkModel();
		
		UserModel user = (UserModel) request.getAttribute("user");
		
		String path = ((HttpServletRequest) request).getRequestURI();
		
		long linkId = 0;
		try {
			linkId = Long.parseLong(URLDecoder.decode(path.toLowerCase().replaceAll("/edit-link/", ""),"UTF-8"));
		} catch (Exception e) {
			response.sendRedirect("/message?txt=page-not-found");
			return;
		}
		
		link = linkData.getLink(linkId);
		
		//Check create link
		if (link == null || user == null || !link.getCreator().equalsIgnoreCase(user.getUsername())) {
			response.sendRedirect("/message?txt=not-permission");
			return;
		}
		
		request.setAttribute("form", "edit");
		request.setAttribute("check", check);
		request.setAttribute("link", link);
		request.setAttribute("categories", categories);
		try {
			request.getRequestDispatcher("/pages/form_link.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		CategoryData cData = new CategoryData();
		LinkData linkData = new LinkData();
		LinkModel link = new LinkModel();
		LinkForm linkForm = new LinkForm();
		
		UserModel user = (UserModel) request.getAttribute("user");
		String path = ((HttpServletRequest) request).getRequestURI();
		
		long linkId = 0;
		try {
			linkId = Long.parseLong(URLDecoder.decode(path.toLowerCase().replaceAll("/edit-link/", ""),"UTF-8"));
		} catch (Exception e) {
			response.sendRedirect("/add-category");
			return;
		}
		link = linkData.getLink(linkId);
		
		//Check create link
		if (link == null || link.getCreator().equalsIgnoreCase(user.getUsername())) {
			response.sendRedirect("/message?txt=not-permission");
			return;
		}
		
		if (link != null)
			link.setLastCategory(link.getCategory());
		
		TreeMap forms = linkForm.checkValid(request, link);
		TreeMap check = (TreeMap) forms.get("checkValid");
		link = (LinkModel) forms.get("link");
		
		String remoteAddr = request.getRemoteAddr();
		ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
		reCaptcha.setPrivateKey("6LeA0c4SAAAAAIadFi6R4xiBkjLDo4jImT2S35LZ");
		
		String challenge = request.getParameter("recaptcha_challenge_field");
		String uresponse = request.getParameter("recaptcha_response_field");
		if(challenge == null)
		{
		        challenge = "b";
		}
		if(uresponse == null)
		{
		        uresponse = "a";
		}
		
		ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);
		
		if (!reCaptchaResponse.isValid()) {
			check.put("captcha", "Invalid Captchar");
		}
		
		if(check.size() == 0)
	    {
			if (user != null) {
				link.setCreator(user.getUsername());
			}
			
			linkData.insert(link);
			request.setAttribute("success", "Update success link " + link.getId());
	    }
		
		ArrayList<CategoryModel> categories = cData.list();
		
		request.setAttribute("form", "edit");
		request.setAttribute("check", check);
		request.setAttribute("categories", categories);
		request.setAttribute("link", link);
		try {
			request.getRequestDispatcher("/pages/form_link.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
